package com.dog.basics.sys.controller;


import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dog.basics.bean.dto.admin.sys.SysUserDto;
import com.dog.basics.bean.dto.admin.sys.SysUserEditDto;
import com.dog.basics.bean.dto.admin.sys.SysUserSaveDto;
import com.dog.basics.bean.dto.admin.sys.UpdatePasswordDto;
import com.dog.basics.bean.model.sys.SysUser;
import com.dog.basics.bean.vo.admin.sys.SysUserPageVo;
import com.dog.basics.common.annotation.SysLog;
import com.dog.basics.common.constant.SwaggerConstants;
import com.dog.basics.common.util.PageParam;
import com.dog.basics.common.util.R;
import com.dog.basics.constant.Constant;
import com.dog.basics.security.annotation.Inner;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.service.sys.SysRoleService;
import com.dog.basics.service.sys.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 系统用户
 * @author dog
 */

@RestController
@AllArgsConstructor
@Api(value = SwaggerConstants.SYSTEM+"系统用户管理模块",tags = SwaggerConstants.SYSTEM+"系统用户管理模块")
@RequestMapping("/sys/user")
public class SysUserController {


	private final SysUserService sysUserService;
	private final PasswordEncoder passwordEncoder;
	private final SysRoleService sysRoleService;
	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	@PreAuthorize("@pms.hasPermission('sys:user:info')")
	public R<SysUser> info(@PathVariable("userId") Long userId){
		SysUser user = sysUserService.getSysUserById(userId);
		user.setUserId(null);
		//获取用户所属的角色列表
		List<Long> roleIdList = sysRoleService.listRoleIdByUserId(userId);
		user.setRoleIdList(roleIdList);
		return R.ok(user);
	}
	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
	public R<SysUser> info(){
		return R.ok(sysUserService.getSysUserById(SecurityUtils.getSysUser().getUserId()));
	}
	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@PostMapping("/password")
	@ApiOperation(value = "修改密码", notes = "sys:user:password")
	@PreAuthorize("@pms.hasPermission('sys:user:password')")
	public R<Boolean> password(@RequestBody @Valid UpdatePasswordDto updatePasswordDto) {
		Long userId = SecurityUtils.getSysUser().getUserId();
		SysUser dbUser = sysUserService.getSysUserById(userId);
		if (!passwordEncoder.matches(updatePasswordDto.getPassword(), dbUser.getPassword())) {
			return R.failed("原密码不正确");
		}
		//新密码
		String newPassword = passwordEncoder.encode(updatePasswordDto.getNewPassword());
//		更新密码
		sysUserService.updatePasswordByUserId(userId, newPassword);
		return R.ok();
	}

	/**
	 * 所有用户列表
	 */
	@GetMapping("/page")
	@ApiOperation(value = "所有用户列表", notes = "sys:user:page")
	@PreAuthorize("@pms.hasPermission('sys:user:page')")
	@Inner
	public R<IPage<SysUserPageVo>> page(PageParam<SysUser> page, SysUserDto dto) {
		return R.ok(sysUserService.getSysUserPage(page, dto));
	}

	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@PostMapping("/save")
	@ApiOperation(value = "保存用户", notes = "sys:user:save")
	@PreAuthorize("@pms.hasPermission('sys:user:save')")
	public R<Boolean> save(@Valid @RequestBody SysUserSaveDto sysUserSaveDto) {
		sysUserService.saveUserAndUserRole(sysUserSaveDto);
		return R.ok();
	}


	/**
	 * 修改用户
	 */

	@SysLog("修改用户")
	@PutMapping("/update")
	@ApiOperation(value = "修改用户", notes = "sys:user:update")
	@PreAuthorize("@pms.hasPermission('sys:user:update')")
	public R<Boolean> update(@Valid @RequestBody SysUserEditDto sysUserEdit) {
		return sysUserService.updateUserAndUserRole(sysUserEdit);
	}

	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@DeleteMapping("/delete")
	@ApiOperation(value = "删除用户", notes = "sys:user:delete")
	@ApiImplicitParam(name = "userIds", value = "系统用户ID", required = true, paramType = "Long[]")
	@PreAuthorize("@pms.hasPermission('sys:user:delete')")
	public R<Boolean> delete(@RequestBody Long[] userIds) {
		if (userIds.length == 0) {
			return R.failed("请选择需要删除的用户");
		}
		if (ArrayUtil.contains(userIds, Constant.SUPER_ADMIN_ID)) {
			return R.failed("系统管A员不能删除");
		}
		if (ArrayUtil.contains(userIds, SecurityUtils.getSysUser().getUserId())) {
			return R.failed("当前用户不能删除");
		}
		sysUserService.deleteBatch(userIds);
		return R.ok();
	}

	/**
	 * 重置密码
	 *
	 * @param sysUserId
	 * @return guonh 2020年2月10日
	 */
	@SysLog("重置密码")
	@PutMapping("/resetPassword/{sysUserId}")
	@ApiImplicitParam(name = "sysUserId", value = "系统用户ID", required = true, paramType = "Long")
	@ApiOperation(value = "重置密码", notes = "sys:user:resetpasswordedit")
	@PreAuthorize("@pms.hasPermission('sys:user:resetpasswordedit')")
	public R<Boolean> editResetPassword(@PathVariable("sysUserId") Long sysUserId) {
		return R.ok(sysUserService.editResetPassword(sysUserId));
	}

	/**
	 * 冻结 - 解封账户
	 *
	 * @param sysUserId
	 * @return guonh 2020年2月10日
	 */

	@SysLog("冻结 - 解封账户")
	@PutMapping("/frozenAccounts/{sysUserId}")
	@ApiOperation(value = "冻结 - 解封账户", notes = "sys:user:frozenaccountsedit")
	@ApiImplicitParam(name = "sysUserId", value = "系统用户ID", required = true, paramType = "Long")
	@PreAuthorize("@pms.hasPermission('sys:user:frozenaccountsedit')")
	public R<Boolean> editFrozenAccounts(@PathVariable("sysUserId") Long sysUserId) {
		return R.ok(sysUserService.editFrozenAccounts(sysUserId));
	}


}
